const { think } = require('thinkjs');
const Base = require('./base.js');
const { default: BigNumber } = require('bignumber.js');
const moment = require('moment/moment.js');

module.exports = class extends Base {
  async listDataAction() {
    const id = this.get('project_id');
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const remark = this.get('remark') || '';
    const type = this.get('type') || '';

    const query = {
      project_id: id,
    };

    if (!think.isEmpty(type)) {
      query.type = type;
    }

    if (!think.isEmpty(remark)) {
      query.remark = ['like', `%${remark}%`];
    }

    const data = await this.model('ac_db')
      .where(query)
      .order(['remark ASC', 'sort ASC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async billAction() {
    const id = this.get('id');
    const remark = this.get('remark');
    const resolve_time = this.get('resolve_time');
    let page = this.get('page') || 1;
    let size = this.get('size') || 20;

    const p = {};

    if (!think.isEmpty(id)) {
      p['a.address'] = id;
    }
    if (!think.isEmpty(remark)) {
      p['b.remark'] = ['like', `%${remark}%`];
    }
    if (!think.isEmpty(resolve_time)) {
      p['a.resolve_time'] = [
        'between',
        moment(resolve_time)
          .startOf('day')
          .format('YYYY-MM-DD HH:mm:ss'),
        moment(resolve_time)
          .endOf('day')
          .format('YYYY-MM-DD HH:mm:ss'),
      ];
      page = 1;
      size = 1000;
    }

    const data = await this.model('ac_db_log')
      .order(['resolve_time DESC'])
      .alias('a')
      .join({
        ac_db: {
          join: 'left',
          as: 'b',
          on: ['address', 'db_id'],
        },
      })
      .field('a.*, b.remark, b.type')
      .where(p)
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async listAllAction() {
    const data = await this.model('ac_db').select();

    return this.success(data);
  }
};
